package cn.xy.ymcc.web.controller;

import cn.xy.ymcc.domain.PayOrder;
import cn.xy.ymcc.dto.AlipayNotifyDto;
import cn.xy.ymcc.dto.PayApplyDto;
import cn.xy.ymcc.result.JSONResult;
import cn.xy.ymcc.service.IPayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private IPayOrderService payOrderService;


    /**
     * 根据订单号查询支付单
     * @param orderNo
     * @return
     */
    @GetMapping("/checkPayOrder/{orderNo}")
    public JSONResult checkPayOrder(@PathVariable("orderNo")String orderNo){
        PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
        return payOrder == null?JSONResult.error():JSONResult.success();

    }

    /**
     * 发起支付申请
     */
    @PostMapping("/apply")
    public JSONResult apply(@RequestBody PayApplyDto payApplyDto){
        //发起支付请求，支付宝返回一个form表单，给到前端。
        String formStr = payOrderService.apply(payApplyDto);
        return JSONResult.success(formStr);

    }

    /**
     * 支付宝的异步回调接口
     * @param dto
     * @return  success 或者别的字符串
     *    如果返回success给支付宝，那么支付宝不再通知你了
     *    如果返回的是非success，那么支付宝会一直尝试通知您，直到8次通知
     */
    @RequestMapping("/alipay/notify")
    public String notify(AlipayNotifyDto dto){
        try {
            System.out.println("支付宝异步回调。。。。。");
            return payOrderService.notify(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return "Fail";
        }
    }



}
